package cn.eeepay.framework.service.impl;

import cn.eeepay.framework.dao.JumpWarnDao;
import cn.eeepay.framework.model.JumpWarn;
import cn.eeepay.framework.model.UserLoginInfo;
import cn.eeepay.framework.service.JumpWarnService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class JumpWarnServiceImpl implements JumpWarnService {

    @Resource
    private JumpWarnDao jumpWarnDao;

    @Override
    public List<JumpWarn> select(){
        List<JumpWarn> select = jumpWarnDao.select();
        if(CollectionUtil.isNotEmpty(select)){
            for (JumpWarn jumpWarn : select) {
                Date warnTime = jumpWarn.getWarnTime();
                String warnTimeStr = DateUtil.formatTime(warnTime);
                jumpWarn.setWarnTimeStr(warnTimeStr);
            }
        }
        return jumpWarnDao.select();
    }

    @Transactional
    @Override
    public void update(List<JumpWarn> list) {
        final UserLoginInfo principal = (UserLoginInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String mender = principal.getUsername();
        List<JumpWarn> old = select();
        List<Integer> oldList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(old)){
            for (JumpWarn jumpWarn : old) {
                oldList.add(jumpWarn.getId());
            }
        }else{
            oldList = new ArrayList<>();
        }
        List<Integer> newList = new ArrayList<>();
        for (JumpWarn jumpWarn : list) {
            jumpWarn.setCreator(mender);
            if(jumpWarn.getId() != null){
                newList.add(jumpWarn.getId());
                jumpWarnDao.update(jumpWarn);
            }else{
                jumpWarn.setWarnStatus(0);
                jumpWarn.setCreateTime(new Date());
                jumpWarnDao.insert(jumpWarn);
            }
        }
        oldList.removeAll(newList);
        for (Integer id : oldList) {
            jumpWarnDao.delete(id);
        }
    }

    @Override
    public void updateLastWarnTime(Integer id, int warnStatus, Date toDay) {
        jumpWarnDao.updateLastWarnTime(id,warnStatus,toDay);
    }

}
